﻿using CPlatePrintSys.Infrastructure;
using CPlatePrintSys.Win.Events;
using MahApps.Metro.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Navigation.Regions;
using System;
using System.Windows.Input;
using System.Windows.Threading;
using CPlatePrintSys.Domain.Models;
using Prism.Navigation;
using CPlatePrintSys.Domain.Events;

namespace CPlatePrintSys.Win.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;
        private DispatcherTimer _timer;
        private User _currentUser;

        public MainWindowViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;


            // 初始化时间
            CurrentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            // 如果没有通过导航参数传递，则订阅事件等待
            _eventAggregator.GetEvent<UserLoggedInEvent>().Subscribe(OnUserLoggedIn, ThreadOption.UIThread, false);


            // 创建并启动定时器
            InitializeTimer();
        }

        private void InitializeTimer()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1); // 1秒间隔
            _timer.Tick += Timer_Tick;
            _timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            CurrentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }


        private string _createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        public string CurrentTime
        {
            get => _createTime;
            set => SetProperty(ref _createTime, value);
        }

        public User CurrentUser
        {
            get => _currentUser;
            set => SetProperty(ref _currentUser, value);
        }


        private void OnUserLoggedIn(User user)
        {
            CurrentUser = user;
        }


        // 析构函数，确保定时器被正确释放
        ~MainWindowViewModel()
        {
            if (_timer != null)
            {
                _timer.Stop();
                _timer.Tick -= Timer_Tick;
            }
        }
    }
}
